﻿<%@ WebHandler Language="C#" Class="sysUserHandler" %>

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

using log4net;
using log4net.Config;

using Web.Library.DomainObject.SQLServer;
using Web.Library.Facade.SQLServer;
using Web.Library.DataAccess.SQLServer;

using Web.Support;
public class sysUserHandler : BaseHandler {
    private SysUserFacade usersFacade = new SysUserFacade(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);


    public override void ProcessRequest(HttpContext context)
    {
        base.ProcessRequest(context);
        context.Response.ContentType = "text/plain";
        string result = Process(context);
        context.Response.Write(result);
    }

    private string Process(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            if (context.Request.QueryString["show"] != null)
            {
                switch (context.Request.QueryString["show"].ToString())
                {

                    case "read": result = this.Read(context); break;
                    case "create": result = this.Create(context); break;
                    case "update": result = this.Update(context); break;
                    case "updateprofile": result = this.UpdateProfile(context); break;
                    case "delete": result = this.Delete(context); break;
                }
            }

            
        }
        catch (Exception ex)
        {
            //result = "{success: false, message: 'Error found on page! " + ConfigurationManager.AppSettings["ErrorHelpText"].ToString() + "'}";
            //log.Debug("Process() on GroupHandler.ashx.cs: " + ex.Message.ToString());

            Logger.Debug("Process () sysUserHandler.ashx", ex);
        }
        return result;
    }

    private string Delete(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            
            usersFacade.Delete(Convert.ToInt32(context.Request.QueryString["Id"].ToString()));
            result = "{\"success\": \"true\"}";
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }


    private string UpdateProfile(HttpContext context)
    {

        context.Response.Clear();
        context.Response.Buffer = true;

        System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

        string jsonString = string.Empty;
        jsonString = context.Server.UrlDecode(sr.ReadToEnd());
        Newtonsoft.Json.Linq.JObject jo = string.IsNullOrEmpty(jsonString) ? null : Newtonsoft.Json.Linq.JObject.Parse(jsonString);

        sr.Close();
        sr.Dispose();

        JSONHelper helper = new JSONHelper();
        try
        {

            SysUser obj = new SysUser();
            obj.UserID = base.UserID;// (int)jo["UserID"];
            obj.Name = (string)jo["Name"];
            obj.Password = (string) jo["PasswordNew"];
            obj.UpdatedBy = base.UserLoggedIn;
            obj.UpdatedDate = DateTime.Now;
            bool error = false;

            if (!string.IsNullOrEmpty((string)jo["PasswordNew"]))
            {
                SysUser getUser = new SysUser();
                bool validate = usersFacade.ValidateUser(base.UserCode, jo["Password"].ToString(),out getUser);
                if (validate)
                {
                    if (!string.IsNullOrEmpty(jo["PasswordNew"].ToString()) && (jo["PasswordNew"].ToString().Trim() == jo["PasswordRetype"].ToString()))
                    {
                        usersFacade.UpdateResetPassword(obj);
                    }
                    else
                    {
                        helper.Message = "Password baru tidak sama. Masukkan kembali password yang baru dengan benar!";
                        error = true;
                        helper.IsSuccess = false;
                    }
                }
                else
                {
                    //InfoSubmit.Text = "Password salah, silakan masukkan password anda yang benar!";
                    helper.Message = "Password salah, silakan masukkan password anda yang benar!";
                    error = true;
                    helper.IsSuccess = false;
                }
                
                //if (new ProfileFacade().getAuthenticationUser(new AuthInfo().UserInfo().EmailAddress, Request.Form["PassCode"].ToString()).ID > 0)
                //{
                //    if (!string.IsNullOrEmpty(Request.Form["PassCode_new"].ToString()) && (Request.Form["PassCode_new"].ToString() == Request.Form["PassCode_retype"].ToString()))
                //    {
                //        new ProfileFacade().ResetPassCode(Request.Form["PassCode_new"].ToString(), profile.ID);
                //    }
                //    else
                //    {
                //        InfoSubmit.Text = "Password baru tidak sama. Masukkan kembali password yang baru dengan benar!";
                //        error = true;
                //    }
                //}
                //else
                //{
                //    InfoSubmit.Text = "Password salah, silakan masukkan password anda yang benar!";
                //    error = true;
                //}
            }

            if (!error)
            {
                //new ProfileFacade().UpdateProfile(profile);
                //InfoSubmit.Text = "Profile berhasil di simpan!";

                usersFacade.UpdateProfile(obj);

                helper.Message = "Profile berhasil di simpan !";
                helper.IsSuccess = true;
            }
            

            

        }
        catch (Exception ex)
        {
            //throw ex;

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }

        //return result;
        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
    }

    
    private string Update(HttpContext context)
    {
       
        
        //string result = string.Empty;
        //try
        //{
        //    SysUser user = new SysUser();
        //    user.UserID = Convert.ToInt32(context.Request.QueryString["models[0][UserID]"].ToString());
        //    user.UserCode = context.Request.QueryString["models[0][UserCode]"].ToString();
        //    user.GroupID = Convert.ToInt32(context.Request.QueryString["models[0][GroupID]"].ToString());
        //    user.GroupAppID = Convert.ToInt32(context.Request.QueryString["models[0][GroupAppID]"].ToString());
        //    user.UpdatedBy = base.UserLoggedIn;
        //    user.UpdatedDate = DateTime.Now;
        //    //user.IsAdmin = Convert.ToBoolean(context.Request.QueryString["models[0][IsAdmin]"].ToString());
        //    usersFacade.Update(user);
        //    result = "{\"success\": \"true\"}";
        //}
        //catch (Exception ex)
        //{
        //    throw ex;
        //}

        //return result;

        context.Response.Clear();
        context.Response.Buffer = true;

        System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

        string jsonString = string.Empty;
        jsonString = context.Server.UrlDecode(sr.ReadToEnd());
        Newtonsoft.Json.Linq.JObject jo = string.IsNullOrEmpty(jsonString) ? null : Newtonsoft.Json.Linq.JObject.Parse(jsonString);

        sr.Close();
        sr.Dispose();

        JSONHelper helper = new JSONHelper();
        try
        {

            SysUser obj = new SysUser();
            obj.UserID = (int)jo["UserID"];
            obj.Name = (string)jo["Name"];
            obj.UserCode = (string)jo["Email"];
            obj.GroupID = (int)jo["GroupID"];
            obj.GroupAppID = (string)jo["GroupAppID"];
            obj.UpdatedBy = base.UserLoggedIn;
            obj.UpdatedDate = DateTime.Now;

            usersFacade.Update(obj);

            helper.Message = "Data berhasil di simpan !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {
            //throw ex;

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }

        //return result;
        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
    }
    
    private string Create(HttpContext context)
    {
        //string result = string.Empty;
        //try
        //{

        //    SysUser user = new SysUser();
        //    user.UserCode = context.Request.QueryString["models[0][UserCode]"].ToString();
        //    user.GroupID = Convert.ToInt32(context.Request.QueryString["models[0][GroupID]"].ToString());
        //    user.GroupAppID = Convert.ToInt32(context.Request.QueryString["models[0][GroupAppID]"].ToString());
        //    user.Password = "welcome";
        //    user.CreatedBy = base.UserLoggedIn;
        //    user.CreatedDate = DateTime.Now;
        //    //user.IsAdmin = Convert.ToBoolean(context.Request.QueryString["models[0][IsAdmin]"].ToString());
        //    usersFacade.Save(user);
        //    result = "{\"success\": \"true\"}";
        //}
        //catch (Exception ex)
        //{
        //    throw ex;
        //}

        //return result;

        //string result = string.Empty;

        context.Response.Clear();
        context.Response.Buffer = true;

        System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

        string jsonString = string.Empty;
        jsonString = context.Server.UrlDecode(sr.ReadToEnd());
        Newtonsoft.Json.Linq.JObject jo = string.IsNullOrEmpty(jsonString) ? null : Newtonsoft.Json.Linq.JObject.Parse(jsonString);

        sr.Close();
        sr.Dispose();
        
        JSONHelper helper = new JSONHelper();
        try
        {

            SysUser obj = new SysUser();
            obj.Name = (string)jo["Name"];
            obj.UserCode = (string)jo["Email"];
            obj.GroupID = (int)jo["GroupID"];
            obj.GroupAppID = (string)jo["GroupAppID"];
            obj.CreatedBy = base.UserLoggedIn;
            obj.CreatedDate = DateTime.Now;

            usersFacade.Save(obj);

            helper.Message = "Data berhasil di simpan !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {
            //throw ex;

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }

        //return result;
        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
    }
    
    private string Read(HttpContext context)
    {
        string result = string.Empty;
        try
        {
            
            string sort = "asc";
            string dir = "SysUser.UserId";
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);
            int pageSize = 10;
            int.TryParse(context.Request.QueryString["pageSize"] ?? "10", out pageSize);
            SysUser users = new SysUser();
            if (context.Request.QueryString["sort[0][dir]"] != null) 
                sort = context.Request.QueryString["sort[0][dir]"].ToString();
            if (context.Request.QueryString["sort[0][field"] != null) 
                dir = context.Request.QueryString["sort[0][field"].ToString();
            //if (context.Request.QueryString["key"] != null) groups.GroupName = context.Request.QueryString["word"].ToString();

            
            List<SysUser> list = new List<SysUser>();
            list = usersFacade.GetListMoreTable(pageSize, page,dir,sort);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            result = "{\"pageSize\": " + list.Count + ", \"data\": " + serializer.Serialize(list) + "}";

            
        }
        catch (Exception ex)
        {
            throw ex;
        }

        return result;
    }

 
    public bool IsReusable {
        get {
            return false;
        }
    }

}